package com.zyl.points.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;

import com.zyl.points.Main;
import com.zyl.points.bean.Question;
import com.zyl.points.csv.CsvReader;

/**
 * 文件工具类
 * 
 * @author zyl 2010-1-6下午02:14:41
 */
public class FileUtil {
	public static final int MAX_FILE_BUFFER_SIZE = 4 * 1024;
	private FileUtil() {
	}
	public static Reader fileToStream(String fileName ) throws FileNotFoundException {
		Reader inputStream = null;
		if (fileName != null) {
			inputStream = new BufferedReader(new InputStreamReader(
					new FileInputStream(fileName), Charset.forName("GBK")),
					 MAX_FILE_BUFFER_SIZE);
		}

		 
		return inputStream;
	}
	/**
	 * 通过File对象创建文件
	 * 
	 * @param file
	 * @param filePath
	 */
	public static List<Question> create(InputStream is) {
		List<Question> list = new ArrayList();
		try {
			 CsvReader reader = new CsvReader(new InputStreamReader(is,Charset.forName("GBK")));
			while (reader.readRecord()) {
				if(!"".equals(reader.get(0).trim())){
				Question question = new Question(reader.get(0),reader.get(1),2);
				list.add(question);
				}
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return list;

	}
	 /**
	  * 创建导入模版
	  * @param is
	  * @param SDPATH
	  * @throws IOException
	  */
	public static void createFile(InputStream is,String SDPATH) throws IOException {
		 String s=SDPATH + "//" +"导入模版.csv";    
         File file = new File(s); 
         
                
         if (!file.exists()) { 
             file.createNewFile(); 
             OutputStream os = new FileOutputStream(file);
             int bytesRead = 0;
             byte[] buffer = new byte[1024];
             while ((bytesRead = is.read(buffer, 0, 1024)) != -1) {
             os.write(buffer, 0, bytesRead);
             }
             os.close();
             is.close();
         } 	
		
	}
	
	public static  void upload(final int position,File[] children,final Context context ) {
		
		 
		List<Question> questions;
		try {
			questions = FileUtil.create(new FileInputStream(children[position].getAbsoluteFile().getPath()));
			new DBHelper(context).reset();
			  for(Question q:questions){
		       		new DBHelper(context).insert(q) ;
		       	  }
			  Dialog alertDialog = new AlertDialog.Builder(context). 
              setTitle("上传成功"). 
              setMessage("返回主页"). 
              setPositiveButton("确定", new DialogInterface.OnClickListener() { 
                  @Override 
                  public void onClick(DialogInterface dialog, int which) { 
                	  Intent intent = new Intent();  
       				  intent.setClass(context,Main.class);  
       				  context.startActivity(intent);  
                  } 
              }). 
              setNegativeButton("取消", new DialogInterface.OnClickListener() { 
                   
                  @Override 
                  public void onClick(DialogInterface dialog, int which) { 
                  } 
              }).create(); 
             alertDialog.show(); 
			  
		} catch (FileNotFoundException e) {
			  
			  Dialog alertDialog = new AlertDialog.Builder(context). 
            setTitle("上传成功"). 
            setMessage("返回主页"). 
            setPositiveButton("确定", new DialogInterface.OnClickListener() { 
                @Override 
                public void onClick(DialogInterface dialog, int which) { 
                	  Intent intent = new Intent();  
       				  intent.setClass(context,Main.class);  
       				  context.startActivity(intent);  
                } 
            }). 
            setNegativeButton("取消", new DialogInterface.OnClickListener() { 
                 
                @Override 
                public void onClick(DialogInterface dialog, int which) { 
                } 
            }).create(); 
            alertDialog.show(); 
		}
		
	}
	
		
 
	/**
	 * 列出某目录下所有的子目录	
	 * @param is
	 * @return
	 */
	public static List<HashMap<String, Object>> listFile(String path) {
		 List<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();   
		
		
		
		File f = new File(path);
		    File[] files = f.listFiles();
		    
		  
		
		    for (int i = 0; i < files.length; i++) {
		        HashMap<String, Object> map =new HashMap<String, Object>();
		    	  if (files[i].isDirectory()) {
			            System.out.println("directory is" + files[i].getName());
			        } else {
			            System.out.println("file is" + files[i].getName());
			        }
		    	
		    	
		    	map.put("file",files[i].getName());
		    	listItem.add(map);
		    }


        return listItem;
		
	}
	
	private static String path = Environment.getExternalStorageDirectory()
	.getPath() + "//mem.txt";

public static void createFile() throws IOException {
File file = new File(path);

if (!file.exists()) {
	file.createNewFile();

}

}

public static String read() throws IOException {
createFile();
BufferedReader br = new BufferedReader(new FileReader(path));

String str = "";

String r = br.readLine();

while (r != null) {
	str += r+"\n";
	r = br.readLine();

}
return str;
}

public static void editTxt(String txt) throws IOException {
createFile();
FileWriter fileWriter = new FileWriter(path);
fileWriter.write(txt);
fileWriter.flush();
fileWriter.close();

}
public static boolean write (String newStr) throws IOException {

     // 先读取原有文件内容，然后进行写入操作

     boolean flag = false;

     String filein = newStr + "\r\n";

     String temp = "";



     FileInputStream fis = null;

     InputStreamReader isr = null;

     BufferedReader br = null;



     FileOutputStream fos = null;

     PrintWriter pw = null;

     try {

         // 文件路径
    	 createFile();
         File file = new File(path);

         // 将文件读入输入流

         fis = new FileInputStream(file);

         isr = new InputStreamReader(fis);

         br = new BufferedReader(isr);

         StringBuffer buf = new StringBuffer();
         // 保存该文件原有的内容
         buf.append(filein);
         while ( (temp = br.readLine()) != null ) {

             buf = buf.append(temp);
             buf = buf.append(System.getProperty("line.separator"));

         }

       



         fos = new FileOutputStream(file);

         pw = new PrintWriter(fos);

         pw.write(buf.toString().toCharArray());

         pw.flush();

         flag = true;

     } catch (IOException e1) {

         throw e1;

     } finally {

         if (pw != null) {

             pw.close();

         }

         if (fos != null) {

             fos.close();

         }

         if (br != null) {

             br.close();

         }

         if (isr != null) {

             isr.close();

         }

         if (fis != null) {

             fis.close();

         }

     }

     return flag;


 }


}
